package com.bcx.wind.workflow.imp.cmd.repositorycmd.windprocesscmd;

import com.bcx.wind.workflow.access.QueryFilter;
import com.bcx.wind.workflow.entity.WindOrder;
import com.bcx.wind.workflow.entity.WindProcess;
import com.bcx.wind.workflow.errorcontext.WindError;
import com.bcx.wind.workflow.interceptor.Command;
import com.bcx.wind.workflow.interceptor.CommandContext;
import com.bcx.wind.workflow.support.Assert;
import com.bcx.wind.workflow.support.ObjectHelper;

import java.util.List;

import static com.bcx.wind.workflow.core.constant.ProcessStatus.RECOVERY;
import static com.bcx.wind.workflow.message.ErrorCode.*;

/**
 * 删除流程定义
 *
 * @author zhanglei
 */
public class RemoveProcessCommand implements Command<Integer> {

    /**
     * 流程定义ID
     */
    private String processId;

    /**
     * 需要删除的流程定义
     */
    private WindProcess windProcess;

    /**
     * 执行数据
     */
    private CommandContext commandContext;

    public RemoveProcessCommand(String processId){
        this.processId = processId;
    }

    @Override
    public Integer executor(CommandContext context) {
        try{
            this.commandContext = context;
            return execute();
        }catch (Exception e){
            return 0;
        }
    }

    private Integer execute(){
        //查询
        queryProcess();
        //校验状态
        checkProcessStatus();
        //删除关联配置数据
        removeAboutProcessConfig();
        //删除缓存数据
        removeCache();
        //执行删除
        return removeProcess();
    }


    private  void  removeCache(){
        this.commandContext.getConfiguration().removeProcessCache(this.processId);
        this.commandContext.getConfiguration().removeProcessConfigCache(processId);
    }

    private int  removeProcess(){
        int ret =  commandContext.access().removeProcessById(this.processId);
        if(ret != 1){
            WindError.error(DATABASE_OPERATE_ERROR,null);
        }
        return ret;
    }

    private void  removeAboutProcessConfig(){
        this.commandContext.access().removeProcessConfigByProcessId(this.processId);
    }


    private  void  queryProcess(){
        this.windProcess = commandContext.access().getProcessDefinitionById(this.processId);
        if(windProcess == null){
            WindError.error(PROCESS_QUERY_NULL,null,this.processId);
        }
    }


    private  void  checkProcessStatus(){
        String status = this.windProcess.getStatus();
        if(!RECOVERY.equals(status)){
            WindError.error(PROCESS_REMOVE_STATUS_ERROR,null);
        }
    }

}
